import { useState, useEffect } from 'react';

type TaskFunction = () => void | Promise<void>;

function useSequentialExecution(
  tasks: TaskFunction[],
  delay: number,
): {
  isRunning: boolean;
  currentIndex: number;
  startExecution: () => void;
  stopExecution: () => void;
} {
  const [isRunning, setIsRunning] = useState(false);
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    if (!isRunning || currentIndex >= tasks.length) {
      return;
    }

    let timeoutId: NodeJS.Timeout;
    let mounted = true;

    const executeTask = async () => {
      try {
        const task = tasks[currentIndex];
        const result = task();

        if (result instanceof Promise) {
          await result;
        }
      } catch (error) {
        console.error(`Error executing task ${currentIndex}:`, error);
      }

      if (!mounted) return;

      if (currentIndex < tasks.length - 1) {
        timeoutId = setTimeout(() => {
          setCurrentIndex((prev) => prev + 1);
        }, delay);
      } else {
        setIsRunning(false);
      }
    };

    executeTask();

    return () => {
      mounted = false;
      clearTimeout(timeoutId);
    };
  }, [isRunning, currentIndex, tasks, delay]);

  const startExecution = () => {
    if (tasks.length === 0) return;

    setIsRunning(true);
    setCurrentIndex(0);
  };

  const stopExecution = () => {
    setIsRunning(false);
  };

  return {
    isRunning,
    currentIndex,
    startExecution,
    stopExecution,
  };
}

export default useSequentialExecution;
